var express = require('express');
var router = express.Router();
const moment = require('moment')

const { searchOne, insertOne } = require('../mysql/sqlutils')
const sqlconfig = require('../mysql/sqlconfig')
// 转换时间戳工具
var sillyDateTime = require("silly-datetime");
// jwt token
const JWT = require('../utils/jwt')
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.post('/login', function (req, res, next) {
  const crypto = require('crypto')
  const sha256 = crypto.createHash('sha256');
  // 为了防止digest报错（一个实例只能调用一次digest方法），所以每次登录都创建一个新的crypto实例
  const { username, password } = req.body
  const loginUser = { username, password }
  if (!username || !password) {
    res.json({ code: 500, message: '用户名或密码不能为空' })
    return
  };
  loginUser.password = sha256.update(password).digest('hex');
  const lastloginIp = req.ip.split(':')[req.ip.split(':').length - 1]
  console.log(loginUser.password, req.ip, 'ip:', req.ip.split(':')[req.ip.split(':').length - 1], username)
  // 登录操作
  const sql = `SELECT * FROM users WHERE username='${loginUser.username}' AND password='${loginUser.password}'`;
  sqlconfig.query(sql, (err, result) => {
    if (err) throw err;
    if (result.length === 0) {
      res.json({
        code: 1,
        message: '用户名或密码错误'
      });
    } else {
      // 验证成功，生成token并返回
      const data = result[0]
      const timestamp = sillyDateTime.format(new Date(), "YYYY-MM-DD HH:mm:ss")//生成时间戳
      const sql = `UPDATE users SET lastLoginTime="${timestamp}", lastloginIp="${lastloginIp}" WHERE userId="${data.userid}"`;
      sqlconfig.query(sql, (err, result) => {
        if (err) throw err;
        const payload = { username: username }; // 按照需求设置payload
        const token = JWT.createToken(payload, '1h'); // 生成token，设置过期时间1小时

        // 将token返回给客户端
        res.json({
          token: token,
          code: 0,
          message: '登录成功'
        });
      })

    }
  });

})
router.post('/addUser', async function (req, res, next) {
  const crypto = require('crypto')
  const sha256 = crypto.createHash('sha256');
  // 为了防止digest报错（一个实例只能调用一次digest方法），所以每次登录都创建一个新的crypto实例
  const { username, password } = req.body;
  // 随机生成 uid
  const uid = moment().get() + '_' + (crypto.randomInt(9999999) + 1) + '';
  const user = { username, password }
  const result = await searchOne('users', 'username', username)
  const role = username == 'admin' ? 'ADMIN' : 'USER'
  user.password = sha256.update(password).digest('hex');
  const timestamp = sillyDateTime.format(new Date(), "YYYY-MM-DD HH:mm:ss")
  if (result.length == 0) {
    insertOne('users', 'userid,username,password,createTime,role,status', uid, user.username, user.password, timestamp, role, 1).then(result => {
      res.status(200).send({
        code: 200,
        message: '会员添加成功！',
      })
    }).catch(err => {
      res.status(500).send({
        code: 500,
        message: err
      })
    })
  } else {
    res.status(200).send({
      code: 500,
      message: '用户名已存在',
    })
  }


})

router.get('/searchList', function (req, res, next) {
  if (JWT.verifyToken(req.headers.token)) {
    const selectSql = "select * from users";
    sqlconfig.query(selectSql, (err, results) => {
      // 查询数据失败
      if (err) {
        console.log(err.message)
        return
      }
      res.status(200).send({
        code: 200,
        message: '查询成功！',
        data: results
      })
      // 查询数据成功
      // 注意：如果执行的是 select 查询语句，则执行的结果是数组
    })
  } else {
    res.status(200).send({
      code: -1,
      message: '请检查登录状态！',
    })
  }



})
module.exports = router;
